/**
 * 网络请求封装
 **/
import { ajax } from './ajax.js'
import { Loading, Message, MessageBox } from 'element-ui'

const handleError = (error) => {
    if(error && error.response && error.response.data) {
        return error.response.data.message
    }
    if(error && error.message) {
        return error.message
    }
    return  '网络似乎有点忙，稍后在试'
}

const execAjax = (ajax, url, objc) => {
    // loading
    let loadingInstance = null
    if (objc.loading) {
        loadingInstance = Loading.service({
            text: '拼命加载中...',
        })
    }

    ajax[objc.method](url, objc.data)
        .then(res => {
            closeLoading(loadingInstance)
            objc.success && objc.success(res.data)
            if (objc.method === 'put' && !objc.noPrompt) {
                Message({
                    center: true,
                    type: 'success',
                    message: objc.promptMessage ? objc.promptMessage : '保存成功'
                })
            }
        })
        .catch(error => {
            closeLoading(loadingInstance)
            Message({
                center: true,
                message: handleError(error)
            })
            objc.fail && objc.fail(error)
        })
}

const fetch = (url, objc = {}) => {
    // 默认请求
    if (!objc.method) {
        objc.method = 'get'
    }
    // **** 客户不喜欢loading mask，所以disable ****
    objc.loading = false
    // **** 客户不喜欢loading mask，所以disable ****
    // 发起请求
    if (objc.method === 'delete' || url.indexOf('/deletion') >= 0) {
        MessageBox.confirm('确定要删除数据么？', '删除提示', {
            type: 'warning'
        })
            .then(() => execAjax(ajax, url, objc))
            .catch(() => console.log('取消删除'))
    } else {
        execAjax(ajax, url, objc)
    }
}

const closeLoading = instance => {
    if (instance) {
        setTimeout(() => {
            instance.close()
        }, 500)
    }
}

export default fetch
